package com.hb.trade.server.project.file.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hb.core.pojo.Attachments;
import com.hb.core.pojo.enums.FirstReviewItemTypeEnum;
import com.hb.core.pojo.project.file.dto.BidFileInfoDTO;
import com.hb.core.pojo.project.file.dto.ReviewItemSecondDto;
import com.hb.core.pojo.project.file.dto.ReviewItemThirdDto;
import com.hb.core.pojo.project.file.entity.ReviewItemFirst;
import com.hb.core.pojo.project.file.entity.ReviewItemSecond;
import com.hb.core.pojo.project.file.mapper.ReviewItemFirstMapper;
import com.hb.core.pojo.project.file.mapper.ReviewItemSecondMapper;
import com.hb.core.pojo.project.file.mapper.ReviewItemThirdMapper;
import com.hb.core.pojo.project.opening.entity.BidOpeningSchedule;
import com.hb.core.pojo.project.section.dto.BidSectionDTO;
import com.hb.core.pojo.project.section.entity.BidSection;
import com.hb.trade.server.project.opening.service.BidOpeningScheduleService;
import com.hb.trade.server.project.section.service.raw.BidSectionService;
import org.fzzn.core.util.Enums;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 招标文件业务逻辑处理层
 *
 * @author zhaojk
 */
public class BidFileInfoManager extends BidFileInfoDTO {

    /**
     * 填充招标文件详情及标段信息
     * 该方法需要将
     * "开标时间"
     * "是否缴纳保证金"
     * "保证金缴纳方式"
     * "价款形式"
     * 填充到招标文件对象中
     * 需要判断这些字段值是否相同
     *
     * @param bidSections
     * @deprecated 原型已修改, 该方法弃用
     */
    @Deprecated
    public void fillSections(List<BidSection> bidSections) {
        Set<LocalDateTime> openBidTimes = CollUtil.set(false); // 开标时间
        Set<Integer> bondFlags = CollUtil.set(false); // 是否缴纳保证金
        //Set<Integer> bondPayTypes = CollUtil.set(false); // 保证金缴纳方式
        Set<Integer> priceForms = CollUtil.set(false); // 价款形式
        Set<BigDecimal> controllerPrice = CollUtil.set(false); // 控制价金额

        for (BidSection bidSection : bidSections) {
            openBidTimes.add(bidSection.getOpenBidTime());
            bondFlags.add(bidSection.getBondFlag());
//            bondPayTypes.add(bidSection.getBondPayType());
            priceForms.add(bidSection.getPriceForm());
            controllerPrice.add(bidSection.getControlPrice());
        }

        BidSectionDTO sectionOptions = getSectionOptions();
        if (sectionOptions == null) {
            sectionOptions = new BidSectionDTO();
        }

        if (openBidTimes.size() == 1) {
            sectionOptions.setOpenBidTime(CollUtil.get(openBidTimes, 0));
        }

        if (bondFlags.size() == 1) {
            sectionOptions.setBondFlag(CollUtil.get(bondFlags, 0));
        }

//        if (bondPayTypes.size() == 1) {
//            sectionOptions.setBondPayType(CollUtil.get(bondPayTypes, 0));
//        }

        if (priceForms.size() == 1) {
            sectionOptions.setPriceForm(CollUtil.get(priceForms, 0));
        }

        if (controllerPrice.size() == 1) {
            sectionOptions.setControlPrice(CollUtil.get(controllerPrice, 0));
        }

        setSectionOptions(sectionOptions);
    }

    /**
     * 验证招标文件是否可以发布
     *
     * @return
     */
    public String canDeploy() {
        Attachments biddingDocumentPdf = getBiddingDocumentPdf();
        if (CollUtil.isEmpty(biddingDocumentPdf)) {
            return "请先保存PDF文件";
        }
        Attachments biddingDocumentSignaturePdf = getBiddingDocumentSignaturePdf();
        if (CollUtil.isEmpty(biddingDocumentSignaturePdf)) {
            return "请先对招标文件签章并保存";
        }
        // 查询是否创建的开标一览表
        BidOpeningScheduleService bidOpeningScheduleService = SpringUtil.getBean(BidOpeningScheduleService.class);
        List<BidOpeningSchedule> bidOpeningSchedules = bidOpeningScheduleService.listByFileId(getId());
        if(CollUtil.isEmpty(bidOpeningSchedules)){
            return "请先保存开标一览表";
        }

        // 简易流程还是标准流程（1，简易，2，标准）
        if (getSimpleOrStandard().equals(2)) {
            // 一级评审下还有没有未填写信息的二级评审
            ReviewItemFirstMapper reviewItemFirstMapper = SpringUtil.getBean(ReviewItemFirstMapper.class);
            ReviewItemSecondMapper reviewItemSecondMapper = SpringUtil.getBean(ReviewItemSecondMapper.class);
            List<ReviewItemSecondDto> reviewItemSecondDtoList = reviewItemSecondMapper.verificationTradeReviewItemFirst(getId());
            for (ReviewItemSecondDto reviewItemSecondDto : reviewItemSecondDtoList) {
                if (null != reviewItemSecondDto.getNum() && reviewItemSecondDto.getNum().equals(0)) {
                    ReviewItemFirst reviewItemFirst = reviewItemFirstMapper.selectById(reviewItemSecondDto.getFirstReviewItemId());
                    return "发布失败，评审项[" + Enums.nameOf(FirstReviewItemTypeEnum.class, reviewItemFirst.getFirstReviewItemType()) + "]信息不完整";
                }
            }
            // 判断二级评审下还有没有未填写信息的三级评审
            ReviewItemThirdMapper reviewItemThirdMapper = SpringUtil.getBean(ReviewItemThirdMapper.class);
            List<ReviewItemThirdDto> reviewItemThirdDtoList = reviewItemThirdMapper.verificationTradeReviewItemSecond(getId());
            for (ReviewItemThirdDto reviewItemThirdDto : reviewItemThirdDtoList) {
                if (null != reviewItemThirdDto.getNum() && reviewItemThirdDto.getNum().equals(0)) {
                    ReviewItemSecond reviewItemSecond = reviewItemSecondMapper.selectById(reviewItemThirdDto.getSecondReviewItemId());
                    return "发布失败，评审项[" + reviewItemSecond.getSecondReviewItemName() + "]信息不完整";
                }
            }
        }

        // 判断是否关联了标段
        BidSectionService sectionService = SpringUtil.getBean(BidSectionService.class);
        QueryWrapper<BidSection> wrapper = BidSection.wrapper();
        wrapper.eq("file_id", getId());
        long count = sectionService.count(wrapper);
        if (count == 0) {
            return "请先为招标文件关联标段";
        }

        return null;
    }

    /**
     * 关联标段时的属性设置
     */
    public void setSectionOptions() {
        // 获取招标文件中的标段信息设置
        String sectionInfo = getSectionInfo();
        if (StrUtil.isEmpty(sectionInfo)) {
            return;
        }
        if (JSONUtil.isJsonObj(sectionInfo)) {
            JSONObject obj = JSONUtil.parseObj(sectionInfo);
            BidSection section = obj.toBean(BidSection.class);

            // 单独处理一下开标时间
            // section.setOpenBidTime(DateUtil.parseDateTime(obj.getStr("openBidTime")));

            setSectionOptions(section.to(BidSectionDTO.class));
        }
    }

    /**
     * 关联标段时的属性设置
     */
    @Override
    public BidSectionDTO getSectionOptions() {
        BidSectionDTO sectionOptions = super.getSectionOptions();
        if (sectionOptions == null) {
            setSectionOptions();
        }
        return super.getSectionOptions();
    }
}
